/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.libarae.client.threads;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.net.SocketTimeoutException;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import org.libarae.communication.ClientInterface;
import org.libarae.communication.common.Book;
import org.libarae.communication.common.Type;
import org.libarae.communication.request.PictureRequest;
import org.libarae.communication.response.PictureResponse;
import org.libarae.communication.response.Response;

/**
 *
 * @author Ben
 */
public class PictureThread extends Thread {
    
    private Book mBook;
    private HasPictureThread mParent;

    public PictureThread(Book mBook, HasPictureThread mParent)
    {
        this.mBook = mBook;
        this.mParent = mParent;
    }

    public void run()
    {
        PictureRequest r = new PictureRequest();

        r.setBid(mBook.getBID());

        Response response = null;

        try
        {
            response = ClientInterface.sendRequest(r);
        }
        catch(SocketTimeoutException e)
        {
            JOptionPane.showMessageDialog(null, "Request timed out. Please try again.");
            return;
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        if(response == null)
        {
            System.err.println("Error sending to or receiving from server.");
        }

        if(response.getStatus() == Response.STATUS_GOOD)
        {
            if(response.getType() != Type.PICTURE)
            {
                System.out.println("Received wrong request. Please submit bug report to http://libarae.googlecode.com/");
                return;
            }
            
            PictureResponse bpr = (PictureResponse)response;

            if(bpr.getImage() == null)
            {
                Image img = (new ImageIcon(getClass().getResource("/res/book.png"))).getImage();

                BufferedImage bimg = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
                Graphics g = bimg.createGraphics();
                g.drawImage(img,0,0,null);
                g.dispose();
                mBook.setPicture(bimg);
            }
            else
            {
                mBook.setPicture(bpr.getImage());
                mParent.displayPicture(mBook.getPicture());
            }
            mParent.displayPicture(mBook.getPicture());
        }

        switch(response.getStatus())
        {
            case PictureResponse.STATUS_FAILED_GENERIC:
                //System.out.println("Something bad happened. We are sorry.");
                this.run();
                break;
            case PictureResponse.STATUS_FAILED_BAD_KEY:
                System.out.println("Bad key. Please re-login to obtain a new one.");
                break;
        }
    }
}
